using UnityEngine;
using System.Collections;

public class PlayerAttack : MonoBehaviour {
	public GameObject player;
	public GameObject target;
	public float attacktimer;
	public float coolDown;
	

	private bool autoattack;
	private float DistanceToTar;
	
	// Use this for initialization
	void Start () {
		player = GameObject.FindGameObjectWithTag("Player");
		attacktimer = 0.0f;
		coolDown = 3.0f;
	}
	
	// Update is called once per frame
	void Update () {
		if(target != null)
		{
			autoattack = !(bool)GetComponent<ThirdPersonController>().StopAttack;
		}
		Debug.Log(autoattack);
		if(attacktimer > 0)
		{
			attacktimer -= Time.deltaTime;
		}
		if(attacktimer < 0 )
		{
			attacktimer = 0;
		
		}
		if(target != null)
		{	
			DistanceToTar = Vector3.Distance(target.transform.position, transform.position);
			ThirdPersonController tpc = (ThirdPersonController)this.GetComponent("ThirdPersonController");
			
			if(DistanceToTar < 2.5f)
			{
				tpc.StopAttackEnemy();
				
				if(autoattack == true && attacktimer == 0)
				{
					Attack();
					attacktimer = coolDown;
				}
				if(Input.GetKeyDown(KeyCode.F)) 
				{
					if(attacktimer == 0)
					{
						Attack();
						attacktimer = coolDown;
					}
				}
			}
			if(Input.GetKeyDown(KeyCode.Alpha1)) 
			{
				AutoAttack();
			}
		}
	}
	
	private void Attack() {
		//float distance = Vector3.Distance(target.transform.position, transform.position);
		
		Vector3 dir = (target.transform.position - transform.position).normalized;
		
		float direction = Vector3.Dot(dir, transform.forward);
		
		
		if(DistanceToTar < 2.5f)
		{
			if(direction > 0)
			{
				EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");
				eh.AdjustCurrentHealth(-25);
			}
		}
	}
		
	private void AutoAttack(){
		
		Debug.Log(target.name);
		
		ThirdPersonController tpc = (ThirdPersonController)this.GetComponent("ThirdPersonController");
		tpc.GoAttackEnemy(target);
	}
}
